package www.bwsensing.com.service.collection;

import www.bwsensing.com.common.thread.NamedThreadFactory;
import www.bwsensing.com.service.collection.database.dataobject.ServiceData;

import java.util.concurrent.*;

/**
 * 采集服务运行容器
 * @author macos-zyj
 */
public class CollectionContainer {
    /**
     * 数据采集线程池
     *     如果处理器无定制线程池，则使用此默认
     */
    private static final ExecutorService COLLECTION_EXECUTOR = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors() + 1,
            Runtime.getRuntime().availableProcessors() + 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1000),
            new NamedThreadFactory("ASYNC-COLLECTION-POOL"));

    private static final ConcurrentHashMap<Integer, ServiceData> SERVICE_CONTAINER = new ConcurrentHashMap<>();


    public static void  startService(Integer keyId, ServiceData service){
        COLLECTION_EXECUTOR.submit(service.getService()::start);
        SERVICE_CONTAINER.put(keyId,service);
    }

    public static void stopService(Integer keyId){
        ServiceData service = SERVICE_CONTAINER.get(keyId);
        if( null != service && null != service.getService() ){
            service.getService().stop();
        }
        SERVICE_CONTAINER.remove(keyId);
    }
}
